package netcom;

import java.util.ArrayList;
import java.util.HashMap;

import netcom.exceptions.ServerUnreachable;
import netcom.messages.BConMessage;
import netcom.messages.ExecutionRequestMessage;

public class NetManager {

	
	private HashMap<String, ServiceInstance> servers;
	
	private ServiceLIstenerThread servT;
	
	private HashMap<Integer, ServerThread> connections;
	public static NetManager instance = null;
	public boolean running = false;
	
	public static NetManager getInstance(){
		if(instance == null) instance = new NetManager();
		return instance;
	}
	
	public NetManager(){
		servT = new  ServiceLIstenerThread();
		servers = new HashMap<String, ServiceInstance>();
		connections = new HashMap<Integer, ServerThread>();
		System.out.println("Setup Listener Thread");
		new Thread(servT).start();
		
		
	}
	
	public boolean isRunning(){
		return running;
	}
	
	
	private int connectionsId = 0;
	public boolean askForServiceExecution(ExecutionRequestMessage mex){
		ServiceInstance inst = null;
		//get server (how find the best one? check maui paper)
		for(String  key: servers.keySet()){
			if(servers.get(key).isServerAlive()){
				inst = servers.get(key);
				break;
			}
		}
		
		if(inst == null) return false;
		
		//generate new connection
		connectionsId++;
		if(connectionsId == Integer.MAX_VALUE){
			connectionsId = 1;
		}
		int id = connectionsId;
		ServerThread t = new ServerThread(id, inst);
		connections.put(id, t);
		try {
			t.sendServerMessage(mex);
		} catch (ServerUnreachable e) {
			e.printStackTrace();
			return false;
		}
		new Thread(t).start();
		return true;
		
	}
	
	public void removeConnection(int cid){
		connections.remove(cid);
	}
	
	public void serviceBconReaceaved(String servIp, BConMessage m){
		ServiceInstance srv = null;
		
		if(servers.keySet().contains(servIp)){
			srv = servers.get(servIp);
		}else{
			srv = new ServiceInstance();
			servers.put(servIp, srv);
		}
		
		
		srv.setLastMessageId(m.getMessageId());
		srv.setServIp(servIp);
		srv.setServName(m.getDevId());
		srv.setServPort(m.getServicePort());
		
		
	}
	
	
	public boolean isServerConnected(){
		//get server (how find the best one? check maui paper)
				for(String  key: servers.keySet()){
					if(servers.get(key).isServerAlive()){
						return true;
					}
				}
		return false;
	}
	
}
